# -*- coding: utf8 -*-
'''
    1.4.3 形态学：对象计数
'''

from PIL import Image
from pylab import array, figure, gray, subplot, title, imshow, axis, show, ones
from scipy.ndimage import measurements, morphology

infile = 'img/haizei.jpg'
im = array(Image.open(infile).convert('L'))

figure()
gray()

subplot(221)
title('Ploting: "Haizei.jpg"')
axis('off')
imshow(im)

im = 1*(im < 128)
labels, nbr_objects = measurements.label(im)
print("Number of objects:", nbr_objects)
subplot(222)
axis('off')
title('After Sign')
imshow(labels)

# 形态学开操作更好地分离各个对象
im_open = morphology.binary_opening(im, ones((9, 5)), iterations=2)
subplot(223)
axis('off')
title('Binary Open')
imshow(im_open)

labels_open, nbr_objects_open = measurements.label(im_open)
print("Number of objects:", nbr_objects_open)
subplot(224)
axis('off')
title('Binary Open After Sign')
imshow(labels_open)

show()
